<template>
  <div class="summary">
    <div class="graph-wrapper">
      <div class="graph">
        <div class="header">
          <div class="title">项目数量</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              v-model="graphStatusList[0]['date']"
              :clearable="false"
              @change="initDatas(0)"
            />
          </div>
        </div>
        <div class="echarts echart1" :ref="el => setChartRef(el, 0)"></div>
      </div>
      <div>
        <div class="graph">
          <div class="header">
            <div class="title">项目验收</div>
            <div>
              <el-date-picker
                style="width: 190px"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="graphStatusList[1]['date']"
                @change="initDatas(1)"
                :clearable="false"
              />
            </div>
          </div>
          <div class="echarts" :ref="el => setChartRef(el, 1)"></div>
        </div>
        <div class="graph" style="margin-top: 10px">
          <div class="header">
            <div class="title">项目分布排行</div>
            <div>
              <el-date-picker
                style="width: 190px"
                type="monthrange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="graphStatusList[2]['date']"
                @change="initDatas(2)"
                :clearable="false"
              />
            </div>
          </div>
          <div class="echarts" :ref="el => setChartRef(el, 2)"></div>
        </div>
      </div>
    </div>
    <div class="graph-3r-wrapper">
      <div class="graph">
        <div class="header">
          <div class="title">项目问题</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[3]['date']"
              @change="initDatas(3)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 3)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">项目问题分布</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[4]['date']"
              @change="initDatas(4)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 4)"></div>
      </div>
      <div class="graph">
        <div class="header">
          <div class="title">项目日报</div>
          <div>
            <el-date-picker
              style="width: 190px"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="graphStatusList[5]['date']"
              @change="initDatas(5)"
              :clearable="false"
            />
          </div>
        </div>
        <div class="echarts" :ref="el => setChartRef(el, 5)"></div>
      </div>
    </div>
    <div class="personnel">
      <div class="title">
        <div>当前项目人员分布</div>
        <el-select v-model="roleId" @change="getProjectUser" size="small" style="width: 200px">
          <el-option v-for="item in roleList" :key="item.name" :label="item.name" :value="item.id" />
        </el-select>
      </div>
      <div class="content">
        <div class="block" v-for="(item, key) in persons" :key="key">
          <div style="display: flex; align-items: center">
            <img :src="item.avatarUrl ? urlResource + item.avatarUrl : avatarUrlImg" class="avatar" />
            <div style="margin-left: 13px">{{ item.name }}</div>
          </div>
          <div style="margin-left: 30px; color: #666666">{{ item.projectName }}</div>
          <el-button type="text" style="font-size: 12px"> {{ item.stageName }} </el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="reportSummary">
import { ref, onMounted, onUnmounted, reactive, getCurrentInstance } from "vue"; // computed
import * as echarts from "echarts";
import { useEcharts } from "@/hooks/useEcharts";
import dayjs from "dayjs";
import {
  chartProject,
  projectCount,
  projectCity,
  projectProblem,
  problemType,
  chartReport,
  projectUser,
  projectRole
} from "@/api/modules/statistics";
import { Dict } from "@/api/interface";
import { getParamByParentIdList } from "@/api/modules/sys";
// import { useUserStore } from "@/stores/modules/user";
import avatarUrlImg from "@/assets/images/avatar.gif";

let timer: NodeJS.Timer;
const urlResource = window?.staticConfig.urlResource;
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
let dictList: Dict.ResDictList = reactive({});
// const userStore = useUserStore();
// const userRoleList = computed(() => userStore.userInfo.userRoleList);
const startTime = dayjs().subtract(1, "year").format("YYYY-MM-DD HH:mm:ss");
const endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");

// echarts通用配置
const getConfig = ({ index, grid, legend, series, graphic, title, tooltip }: any) => {
  let data = {
    grid: { left: 30, right: 20, top: 20, bottom: 20, ...grid },
    legend,
    tooltip,
    title,
    xAxis: {
      show: index !== 1,
      type: "category",
      data: graphStatusList.value[index]["data"]["xAxis"],
      axisTick: { show: false },
      axisLine: {
        show: true,
        lineStyle: { color: "#EBEBEB" }
      },
      axisLabel: { color: "#333333", interval: 0 }
    },
    yAxis: {
      show: index !== 1,
      type: "value",
      axisLine: {
        show: true,
        lineStyle: { color: "#EBEBEB" }
      },
      axisTick: { show: true },
      splitLine: { show: false },
      axisLabel: { color: "#333333" },
      minInterval: 1
    },
    graphic,
    series: Array.isArray(series)
      ? series
      : {
          data: graphStatusList.value[index]["data"]["series"],
          ...series
        }
  };
  return data;
};

const graphStatusList = ref([
  { title: "项目数量", date: [startTime, endTime], data: {}, fetchData: projectCount },
  {
    title: "项目验收",
    date: [startTime, endTime],
    data: { series: {} },
    fetchData: chartProject
  },
  { title: "项目分布排行", date: [startTime, endTime], data: {}, fetchData: projectCity },
  { title: "项目问题", date: [startTime, endTime], data: {}, fetchData: projectProblem },
  { title: "项目问题分布", date: [startTime, endTime], data: {}, fetchData: problemType },
  { title: "项目日报", date: [startTime, endTime], data: {}, fetchData: chartReport }
]);

const chartRefs = ref<(HTMLElement | null)[]>([]);
const setChartRef = (el: HTMLElement | null, index: number) => {
  chartRefs.value[index] = el;
};

// 初始化图标数据
const initDatas = async (index: number | null = null) => {
  if (index === null) {
    for (let i = 0; i < graphStatusList.value.length; i++) {
      await fetchData(i);
    }
  } else {
    // 处理时间值
    const end = dayjs(dayjs(graphStatusList.value[index].date[1]).add(1, "month").subtract(1, "day")).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    graphStatusList.value[index].date = [dayjs(graphStatusList.value[index].date[0]).format("YYYY-MM-DD HH:mm:ss"), end];
    await fetchData(index);
    initChart();
  }
};
// 获取字典数据
const getDicList = async () => {
  const list: string[] = [dict.projectStage, dict.projectStatus, dict.questionId, dict.importance];
  const { data } = await getParamByParentIdList({ parentIdList: list.join(",") });
  dictList = data;
};
// 转换显示
const conversionDisplay = (id: string, type: string) => {
  const listItem = dictList[type]?.find(item => item.id === id);
  return listItem?.name;
};
const fetchData = async (index: number) => {
  const [startTime, endTime] = graphStatusList.value[index].date;
  let eData = {};
  const { data } = await graphStatusList.value[index].fetchData({ startTime, endTime });
  if (index === 0) {
    // 处理数据，生成年月数组
    const yearMonths = Array.from(new Set(data.map(item => item.month.substring(0, 7))));
    const allStatus = Array.from(new Set(data.map(item => item.status)));
    let series = allStatus.map(status => ({
      name: conversionDisplay(status, dict.projectStatus),
      type: "line",
      data: new Array(yearMonths.length) // 创建一个与年月数组长度相同的初始数据数组，初始值为0
    }));

    // 填充 series 中的数据
    data.forEach(item => {
      const monthIndex = yearMonths.indexOf(item.month.substring(0, 7));
      const statusIndex = allStatus.indexOf(item.status);
      series[statusIndex].data[monthIndex] = item.value;
    });
    eData = {
      xAxis: yearMonths,
      series: data
    };
  }
  switch (index) {
    case 1:
      eData = { series: data };
      break;
    case 2:
      eData = {
        xAxis: data.map(item => item.city),
        series: data.map(item => item.value)
      };
      break;
    case 3:
    case 5:
      eData = {
        xAxis: data.map(item => item.month),
        series: data.map(item => item.value)
      };
      break;
    case 4:
      eData = {
        xAxis: data.map(item => item.name),
        series: data.map(item => item.value)
      };
      break;
  }

  graphStatusList.value[index].data = eData;
};

// 初始化所有图表
const initChart = async () => {
  const options = [
    // 图表1
    getConfig({
      index: 0,
      grid: { top: 40 },
      legend: { show: true, itemWidth: 10, itemHeight: 10, right: "0%", top: 10 },
      series: { type: "line" }
    }),
    // 图表2
    getConfig({
      index: 1,
      series: [
        {
          type: "pie",
          radius: ["48", "30"],
          center: ["13%", "50%"],
          data: [
            {
              value: graphStatusList.value[1]["data"]["series"]["acceptance"],
              itemStyle: { color: "#74D98C" },
              label: {
                show: true,
                position: "center",
                formatter: function (params: any) {
                  return params.percent + "%";
                }
              }
            },
            { value: 1 - graphStatusList.value[1]["data"]["series"]["acceptance"], itemStyle: { color: "#ECF1F5" } }
          ]
        },
        {
          type: "pie",
          radius: ["48", "30"],
          center: ["50%", "50%"],
          data: [
            {
              value: graphStatusList.value[1]["data"]["series"]["extension"],
              itemStyle: { color: "#F8D27C" },
              label: {
                show: true,
                position: "center",
                formatter: function (params: any) {
                  return params.percent + "%";
                }
              }
            },
            { value: 1 - graphStatusList.value[1]["data"]["series"]["extension"], itemStyle: { color: "#ECF1F5" } }
          ]
        },
        {
          emphasis: { disabled: true },
          type: "pie",
          radius: ["48", "30"],
          center: ["87%", "50%"],
          data: [
            {
              value: graphStatusList.value[1]["data"]["series"]["averageAcceptanceDay"],
              itemStyle: { color: "#F8D27C" },
              label: {
                show: true,
                position: "center",
                formatter: function (params: any) {
                  // console.log(params);
                  return params.value + "天";
                }
              }
            }
            // { value: 1 - graphStatusList.value[1]["data"]["series"]["averageAcceptanceDay"], itemStyle: { color: "#ECF1F5" } }
          ]
        }
      ],
      // tooltip: {
      //   trigger: "item"
      // },
      title: [
        {
          text: "项目验收率",
          left: "13%",
          textStyle: {
            fontSize: 12,
            fontWeight: "normal",
            color: "#333",
            textAlign: "center"
          },
          textAlign: "center",
          top: "80%" //标题文字距离顶部距离
        },
        {
          text: "验收延期率",
          left: "50%",
          textAlign: "center",
          textStyle: {
            fontSize: 12,
            fontWeight: "normal",
            color: "#333",
            textAlign: "center"
          },
          top: "80%" //标题文字距离顶部距离
        },
        {
          text: "平均验收周期",
          left: "87%",
          textAlign: "center",
          textStyle: {
            fontSize: 12,
            fontWeight: "normal",
            color: "#333",
            textAlign: "center"
          },
          top: "80%" //标题文字距离顶部距离
        }
      ]
      // graphic: [
      //   {
      //     type: "text",
      //     left: "7%", // 你可以根据位置调整 left 和 top
      //     bottom: "10%", // 假设这是第一个饼图的下方位置
      //     style: {
      //       text: "项目验收率",
      //       textAlign: "center",
      //       fill: "#000" // 文本颜色
      //     }
      //   },
      //   {
      //     type: "text",
      //     left: "center", // 你可以根据位置调整 left 和 top
      //     bottom: "10%", // 假设这是第一个饼图的下方位置
      //     style: {
      //       text: "验收延期率",
      //       textAlign: "center",
      //       fill: "#000" // 文本颜色
      //     }
      //   },
      //   {
      //     type: "text",
      //     right: "6%", // 你可以根据位置调整 left 和 top
      //     bottom: "10%", // 假设这是第一个饼图的下方位置
      //     style: {
      //       text: "平均验收周期",
      //       textAlign: "center",
      //       fill: "#000" // 文本颜色
      //     }
      //   }
      // ]
    }),

    // 图表3
    getConfig({
      index: 2,
      series: {
        type: "bar",
        itemStyle: { color: (params: any) => (params.dataIndex === 0 ? "#5378F6" : "#ECF1F5") },
        barWidth: 20,
        emphasis: { disabled: true }
      }
    }),

    // 图表4
    getConfig({
      index: 3,
      series: {
        type: "line",
        itemStyle: { color: "#5378F6" }
      }
    }),

    // 图表5
    getConfig({
      index: 4,
      series: {
        type: "bar",
        itemStyle: { color: (params: any) => (params.dataIndex === 0 ? "#5378F6" : "#ECF1F5") },
        barWidth: 20,
        emphasis: { disabled: true }
      }
    }),

    // 图表6
    getConfig({
      index: 5,
      series: {
        type: "line",
        itemStyle: { color: "#5378F6" }
      }
    })
  ];
  chartRefs.value.map((chartRef, index) => {
    const myChart: echarts.ECharts = echarts.init(chartRef as HTMLElement);
    useEcharts(myChart, options[index]);
  });
};

// 人员分布
const roleId = ref();
const roleList = ref([]);
const persons = ref([]);
const getListAllRole = async () => {
  const { data } = await projectRole();
  roleList.value = data;
  roleId.value = roleList.value[0].id;
  getProjectUser();
};
const getProjectUser = async () => {
  const { data } = await projectUser({ roleId: roleId.value });
  const processedUsers = data.reduce((acc, user) => {
    if (user.projects.length > 0) {
      user.projects.forEach(project => {
        acc.push({
          stageName: conversionDisplay(project.progressId, dict.projectStage),
          name: user.name,
          avatarUrl: user.avatarUrl,
          projectName: project.projectName,
          projectAvatarUrl: project.avatarUrl
        });
      });
    }
    return acc;
  }, []);
  // 输出结果
  persons.value = processedUsers;
};

onMounted(async () => {
  getDicList();
  getListAllRole();

  await initDatas();
  initChart();
});
onUnmounted(() => {
  clearInterval(timer);
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
